/**
* leaflet中加载的要素（layer下的）：包含  feature属性：记录geometry_坐标 和 properties_属性
*                           option属性：绘制属性，颜色边界
*
* leaflet中加载的图层(map下的)：包含  _layers属性：是ID和对应feature组成的一系列键值对
*                           option属性：绘制属性，颜色边界
*/

<style scoped>
  .el-button {
    width: 100px;
  }

  #leafletPopupContainer2 {
    width: 400px;
    height: 400px;
    background-color: #2c3e50;
  }

  .leaflet-custom-popup2 {
    width: 400px;
    height: 400px;
    background-color: #2c3e50;
  }
</style>
<template>
  <div class="wrapper" style="position: absolute; z-index: 200;top: 14px;width: auto">
    <div class="selectModelType">
      <div class="tip"><p>Echart Popup</p></div>
      <el-button type="primary" size="mini" @click="test()">测试</el-button>
      <el-button type="primary" size="mini" @click="getBoundary()">蒙版</el-button>
      <br><br>
      <el-button type="primary" size="mini" @click="testPolygon()">Polygon</el-button>
      <el-button type="primary" size="mini" @click="turf_mask()">挖洞</el-button>
      <br><br>
      <el-button type="primary" size="mini" @click="turf_union()">合并</el-button>

    </div>
  </div>
</template>

<script>
  import 'element-ui/lib/theme-chalk/base.css';
  import {eventBus, Gisevevts} from "../../script/events";
  import {getDbData} from "../../script/data-management";
  import CustomPopup from "../widget/related-jsFile/customPopup";
  import Vue from "vue";
  import CreateMarker_pop from "../widget/CreateMarker_pop";
  import BoundaryMask from '../../script/BoundaryMask.js'


  import {polygon} from '@turf/helpers';
  import mask from '@turf/mask';
  import union from '@turf/union';
  // import mask from '@turf/mask';

  export default {
    name: "echartPopup",
    data() {
      return {
        regionJsonDb: null,//IndexedDB对象
        myChart: null,//echart实力
        popup: null,//弹窗
        tempClickRegion: null,//点击时的图层
        boundaryPlygn: null,  //蒙版
      }
    },
    components: {},
    created() {//页面渲染前，即通常初始化某些属性值，然后再渲染成视图
    },
    mounted() {//页面渲染完成后，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作
      leafletMap.on('zoomend', () => {
        if (leafletMap.getZoom() < 6 && this.tempClickRegion) {
          leafletMap.removeLayer(this.tempClickRegion);
          this.tempClickRegion = null;
        }
      });
    },
    watch: {},
    methods: {
      async test() {
        let isMoving = false;
        let onEachFeature = (feature, layer) => {//给图层内每个要素绑定单击
          let tempOverRegion;
          layer.on({
            click: () => {//鼠标点击事件
              isMoving = !isMoving;
              if (this.tempClickRegion) leafletMap.removeLayer(this.tempClickRegion);
              const bounds = layer.getBounds();
              leafletMap.flyToBounds(bounds);
              leafletMap.once("moveend", () => {
                if (tempOverRegion) leafletMap.removeLayer(tempOverRegion);
                isMoving = false;

                this.tempClickRegion = L.geoJSON(feature, {
                  fillColor: "rgba(57,255,68,0.25)",
                  fillOpacity: 0.5,
                  color: "rgba(3,52,255,0.76)",
                  weight: 4,
                  interactive: false//禁止交互，此时图层相当于底图
                }).addTo(leafletMap);
              });
              this.createPopup(feature, layer);
            },
            mouseover: () => {
              if (!isMoving) {
                tempOverRegion = L.geoJSON(feature, {
                  fillColor: "rgba(57,255,68,0.25)",
                  fillOpacity: 0.5,
                  color: "rgba(3,52,255,0.76)",
                  weight: 4,
                  interactive: false//禁止交互，此时图层相当于底图
                }).addTo(leafletMap);
              }
            },
            mouseout: () => {
              if (!isMoving && tempOverRegion) {
                leafletMap.removeLayer(tempOverRegion);
                tempOverRegion = null;
              }
            }
          });
        };
        let options = {
          fillColor: "rgba(57,255,68,0.25)",
          fillOpacity: 0.5,
          color: "rgba(95,116,255,0.55)",
          weight: 6,
          onEachFeature
        };
        let geoData = await getDbData('static/data/china.json', '全国', true);
        let layerGeo = L.geoJSON(geoData, options);
        eventBus.$emit(Gisevevts["handlerAddGeojson"], layerGeo);
        layerGeo.addTo(leafletMap);
      },

      async createPopup(feature, layer) {
        if (this.myChart) this.myChart.dispose();

        //拿到该城市的数据
        let education = await getDbData('static/data/education.json', 'educationDatas');
        let educationData = education['data'];
        let theData = educationData[this._.findIndex(educationData, function (o) {
          return o['省级行政区'] === feature.properties.name;
        })];

        if (!this.popup) this.popup = L.popup().setContent('<div style="width: 220px; height: 220px;" id="markerId"></div>');
        this.popup
          .setLatLng(this._.reverse(feature.properties.center))
          .openOn(leafletMap);

        if (this.myChart) this.myChart.dispose();

        // 基于准备好的dom，初始化echarts实例
        this.myChart = this.$echarts.init(document.getElementById('markerId'));
        // 指定图表的配置项和数据
        let option = {
          tooltip: {
            trigger: 'axis'
          },
          xAxis: [{
            type: 'category',
            data: ['1月', '2月', '3月', '4月']
          }],
          yAxis: [{
            type: 'value',
            name: '水量',
            min: 0,
            max: 50,
            interval: 50,
            axisLabel: {
              formatter: '{value} ml'
            }
          }, {
            type: 'value',
            name: '温度',
            min: 0,
            max: 10,
            interval: 5,
            axisLabel: {
              formatter: '{value} °C'
            }
          }],
          series: [{
            name: '蒸发量',
            type: 'bar',
            data: [2.0, 4.9, 7.0, 23.2]
          }, {
            name: '降水量',
            type: 'bar',
            data: [2.6, 5.9, 9.0, 26.4]
          }, {
            name: '平均温度',
            type: 'line',
            yAxisIndex: 1,
            data: [2.0, 2.2, 3.3, 4.5]
          }]
        };
        // 使用刚指定的配置项和数据显示图表。
        this.myChart.setOption(option);


        // let Toast = Vue.extend(CreateMarker_pop);//Vue.extend创建构造器，参数为一个vue组件
        // let popupContent = new Toast();
        // popupContent.$mount("#leafletPopupContainer");//把PromptBoxLeaflet组件挂载到#leafletPopupContainer中
        // popupContent.openPrompt(marker);
        // popupContent.$on("click-close", () =>{
        //   // if (this.popupLayer && this.popupLayer.isOpen()) {
        //   leafletMap.closePopup(popUpLayer);
        //   // }
        // });
        // popupContent.$on("save-change", (e) =>{
        //   //无法动态给marker点加图标，需要移除再添加
        //   leafletMap.removeLayer(this.curMarker);
        //   this.curMarker = this.createIconMarker(e);
        // });
      },
      addBoundary() {
        //添加蒙版
        // BoundaryMask
        let option = {};
        //option.extent = [73.0, 3.0, 136.0, 59.0];//遮罩矩形范围，默认xmin,ymin,xmax,ymax
        option.color = '#000000';
        option.opacity = 0.8;
        option.url = "http://yapi.fpi-inc.site/mock/805/one-map/one-map/mock/city/hangzhou";
        new BoundaryMask(leafletMap, option);
      },
      //蒙版加载
      getBoundary() {
        if (this.boundaryPlygn) leafletMap.removeLayer(this.boundaryPlygn)
        let color = 'rgb(0,0,0)'
        let opacity = 0.5;

        $.ajaxSettings.async = false
        $.getJSON('static/data/LiuPanShui/afterEdit.json', (data) => {
          this.boundaryPlygn = this.drawBoundary(data.features[0].geometry.coordinates, color, opacity)
          leafletMap.addLayer(this.boundaryPlygn)
        })
        $.ajaxSettings.async = true;

      },
      //反选 添加外部边界
      drawBoundary(list, color, opacity) {
        //定义中国东南西北端点，作为第一层
        let pNW = {lat: 59.0, lng: 73.0};
        let pNE = {lat: 59.0, lng: 136.0};
        let pSE = {lat: 3.0, lng: 136.0};
        let pSW = {lat: 3.0, lng: 73.0};
        //向数组中添加一次闭合多边形，并将西北角再加一次作为之后画闭合区域的起点
        let pArray = [];
        pArray.push(pNW);
        pArray.push(pSW);
        pArray.push(pSE);
        pArray.push(pNE);
        pArray.push(pNW);
        //循环添加各闭合区域
        for (let i = 0; i < list.length; i++) {
          let points = [];
          $.each(list[i], function (k, v) {
            points.push({lat: v[1], lng: v[0]});
          });
          //将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
          pArray = pArray.concat(points);
          pArray.push(pArray[0]);
        }
        // this.turf_mask(pArray)
        //添加遮蔽层
        return L.polygon(pArray, {color: 'transparent', fillColor: color, fillOpacity: opacity}); //建立多边形覆盖物
      },
      /*
        turf初试
        经过实验发现，已经有孔的面数据，无法再用马mask、函数挖洞
       */
      turf_mask(pArray) {
        let polygoner01 = polygon([[[112, -21], [116, -36], [146, -39], [153, -24], [133, -10], [112, -21]]]);
        let polygoner02 = polygon([[[73, 59], [136, 59], [136, 3.0], [73, 3.0], [73, 59]]]);

        let polygoner03 = polygon([[[90, -55], [170, -55], [170, 10], [90, 10], [90, -55]]]);
        let polygoner04 = polygon([[[-180, -80], [-180, 80,], [180, 80], [180, -80], [-180, -80]]]);


        let masker01 = mask(polygoner01, polygoner04);
        let masker02 = mask(polygoner02, masker01);

        let layerGeo = L.geoJSON(masker02, {
          fillColor: "#FF0000",
          fillOpacity: 0.5,
          color: "#FF0000",
          weight: 1
        });
        layerGeo.addTo(leafletMap);

        // 此时masker中的坐标 经纬度与leaflet正好相反，需要递归函数来实现反转
        // masker.geometry.coordinates 是个[ [ [坐标对],[坐标对],[坐标对] ], [ [坐标对],[坐标对],[坐标对] ]]
        // let temp = this.recursiveFunc(masker.geometry.coordinates)
        // masker.geometry.coordinates = temp

        // let temp2 = this.recursiveFunc(polygoner01.geometry.coordinates)
        // polygoner01.geometry.coordinates = temp2
      },
      //一个递归函数
      recursiveFunc(coordinates) {
        coordinates.forEach((item, index, array) => {
          //执行代码
          if (item[0] instanceof Array) { //当前item不是坐标对时 = true
            array[index] = this.recursiveFunc(item)
          } else {
            array[index] = item.reverse()
          }
        })
        return coordinates
      },
      testPolygon() {
        let latlngs = [
          [ // first polygon
            [[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]], // outer ring
            [[37.29, -108.58], [40.71, -108.58], [40.71, -102.50], [37.29, -102.50]] // hole
          ],
          [ // second polygon
            [[41, -111.03], [45, -111.04], [45, -104.05], [41, -104.05]]
          ]
        ];

        let polygon = L.polygon(latlngs, {color: 'red'}).addTo(leafletMap);
        leafletMap.fitBounds(polygon.getBounds());
      },
      //合并多个多边形
      turf_union() {
        $.getJSON('static/data/turf/test_union.json', (data) => {
          let count = data.features.length
          console.log(count)
          //union
          let polygonArr = []
          let unionPolygon;

          // data.features.forEach((feature, index) => {
          //   if (index === 0){
          //     unionPolygon = polygon(feature.geometry.coordinates[0])  // 获取第一个坐标（仅）
          //   } else {
          //     unionPolygon = union()
          //   }
          // })

          let poly1 = polygon([[
            [-82.574787, 35.594087],
            [-82.574787, 35.615581],
            [-82.545261, 35.615581],
            [-82.545261, 35.594087],
            [-82.574787, 35.594087]
          ]], {"fill": "#0f0"});
          let test01 = polygon(data.features[0].geometry.coordinates[0]);

          let poly2 = polygon([[
            [-82.560024, 35.585153],
            [-82.560024, 35.602602],
            [-82.52964, 35.602602],
            [-82.52964, 35.585153],
            [-82.560024, 35.585153]
          ]], {"fill": "#00f"});
          let test02 = polygon(data.features[1].geometry.coordinates[0]);


          let testUnion = union(poly1, poly2);
          // let testUnion02 = union(test01, test02);

          let tempArr = [test01, test02];
          let testUnion02 = union(...tempArr);


          let layerGeo = L.geoJSON(testUnion02, {
            fillColor: "#FF0000",
            fillOpacity: 0.5,
            color: "#FF0000",
            weight: 1
          });
          layerGeo.addTo(leafletMap);


        })

      },


    },

    destroyed() {


    },
  }
</script>


